package com.jxc.service.impl;

import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.Hibernate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jxc.dao.BaseDaoI;
import com.jxc.model.po.Goods;
import com.jxc.model.po.GoodsRepertory;
import com.jxc.model.po.Repertory;
import com.jxc.model.po.Transferlist;
import com.jxc.model.po.TransferlistItem;
import com.jxc.model.po.User;
import com.jxc.model.vo.DataGrid;
import com.jxc.model.vo.VGoodsRepertory;
import com.jxc.model.vo.VTransferlist;
import com.jxc.service.TransferlistServiceI;

@Service("transferlistService")
public class TransferlistServiceImpl implements TransferlistServiceI {

	@Autowired
	private BaseDaoI<Transferlist> transferlistDao;
	@Autowired
	private BaseDaoI<TransferlistItem> transferitemDao;
	@Autowired
	private BaseDaoI<Goods> goodsDao;
	@Autowired
	private BaseDaoI<GoodsRepertory> goodsreperDao;
	@Override
	public List<VTransferlist> combobox(VTransferlist vtl) {
		return this.changeModel(this.find(vtl));
	}

	@Override
	public List<VTransferlist> search(VTransferlist vtl) {
		List<Transferlist> tls = this.find(vtl);
		try {
			for (Transferlist tl : tls) {
				Hibernate.initialize(tl.getItems());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return this.changeModel(tls);
	}

	@Override
	public DataGrid datagrid(VTransferlist vtl) {
		vtl.setSort("date");
		vtl.setOrder("desc");
		DataGrid dg = new DataGrid();
		dg.setRows(this.changeModel(this.find(vtl)));
		dg.setTotal(this.total(vtl));
		return dg;
	}

	@Override
	public void delete(String ids) {
		// TODO 是否是物理删除,还要级联删除调拔单明细
		if (ids != null) {
			for (String id : ids.split(",")) {
				if (!id.trim().equals("0")) {
					Transferlist tl = transferlistDao.get(Transferlist.class, Long.parseLong(id.trim()));
					if (tl != null) {
						transferlistDao.delete(tl);
					}
				}
			}
		}
	}

	@Override
	public Long save(VTransferlist vtl) {
		Transferlist tl = new Transferlist();
		BeanUtils.copyProperties(vtl, tl);
		if (vtl.getUid() != null) {
			tl.setUser(new User(vtl.getUid()));
		}
		if (vtl.getIcuid() != null) {
			tl.setInConfirmUser(new User(vtl.getIcuid()));
		}
		if (vtl.getOcuid() != null) {
			tl.setOutConfirmUser(new User(vtl.getOrid()));
		}
		if (vtl.getIrid() != null) {
			tl.setInRepertory(new Repertory(vtl.getIrid()));
		}
		if (vtl.getOrid() != null) {
			tl.setOutRepertory(new Repertory(vtl.getOrid()));
		}
		if(vtl.getDate()!=null){
			java.sql.Timestamp time = new java.sql.Timestamp(new java.util.Date().getTime());
			int h = time.getHours();//时
			int f = time.getMinutes();//分
			int m = time.getSeconds();//秒
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			//年月日
			int y = vtl.getDate().getYear()+1900;
			int yf = vtl.getDate().getMonth()+1;
			int day = vtl.getDate().getDate();
			String str = y+"-"+yf+"-"+day+" "+h+":"+f+":"+m;	
			try {
				Date d = sdf.parse(str);
				tl.setDate(d);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		tl.setIsInConfirm(false);
		tl.setIsOutConfirm(false);
		this.transferlistDao.save(tl);
		return tl.getId();
	}

	@Override
	public void update(VTransferlist vtl) {
		Transferlist tl = transferlistDao.get(Transferlist.class, vtl.getId());
		BeanUtils.copyProperties(vtl, tl, new String[] { "id" });
		if (vtl.getUid() != null) {
			tl.setUser(new User(vtl.getUid()));
		}
		if (vtl.getIcuid() != null) {
			tl.setInConfirmUser(new User(vtl.getIcuid()));
		}
		if (vtl.getOcuid() != null) {
			tl.setOutConfirmUser(new User(vtl.getOcuid()));
		}
		if (vtl.getIrid() != null) {
			tl.setInRepertory(new Repertory(vtl.getIrid()));
		}
		if (vtl.getOrid() != null) {
			tl.setOutRepertory(new Repertory(vtl.getOrid()));
		}
	
		this.transferlistDao.update(tl);
		if(vtl.getIds()!=null&&vtl.getIids()!=null&&vtl.getNums()!=null){
			String gid[] = vtl.getIds().trim().split(",");
			String iid[] = vtl.getIids().trim().split(",");
			String num[] = vtl.getNums().trim().split(",");
			for (int i = 0; i < iid.length; i++) {
				if(!iid[i].equals("*")&&iid[i]!="*"){
				   TransferlistItem fis = transferitemDao.get(TransferlistItem.class, new Long(iid[i]));
				  // Goods g = 
				   fis.setNum(new Integer(num[i]));
				   transferitemDao.update(fis);
				}else {
					TransferlistItem fis = new TransferlistItem();
					Goods goods =  goodsDao.get(Goods.class, new Long(gid[i]));
					fis.setGoods(goods);
					fis.setNum(new Integer(num[i]));
					fis.setTransferlist(tl);
					transferitemDao.save(fis);
					
//					vgoodsrepertory vg = new vgoodsrepertory();
//					vg.setgid(new long(gid[i]));
//					vg.set
					String sql = "select t from GoodsRepertory t where t.goods.id="+new Long(gid[i])+" and t.repertory.id="+vtl.getOcuid();
					List<GoodsRepertory> gr = goodsreperDao.find(sql);
					for(GoodsRepertory ff : gr){
						GoodsRepertory cr = goodsreperDao.get(GoodsRepertory.class, ff.getId());
						cr.setNum(cr.getNum()-new Integer(num[i]));
						goodsreperDao.update(cr);
					}
					String sql2 = "select t from GoodsRepertory t where t.goods.id="+new Long(gid[i])+" and t.repertory.id="+vtl.getIcuid();
					List<GoodsRepertory> gr2 = goodsreperDao.find(sql2);
					if(gr2.size()==0){
						GoodsRepertory cr = new GoodsRepertory();
						cr.setGoods(goods);
						cr.setRepertory(new Repertory(vtl.getIrid()));
						cr.setNum(new Integer(num[i]));       
						goodsreperDao.save(cr);
					}else {
						for(GoodsRepertory ff : gr2){
							GoodsRepertory cr = goodsreperDao.get(GoodsRepertory.class, ff.getId());
							cr.setNum(cr.getNum()+new Integer(num[i]));
							goodsreperDao.update(cr);
						}
					}
				}
			}
				
			
		}
		
	}

	private List<VTransferlist> changeModel(List<Transferlist> tls) {
		List<VTransferlist> vtls = new ArrayList<VTransferlist>();
		try {
			if (tls != null && tls.size() > 0) {
				for (Transferlist tl : tls) {
					VTransferlist vtl = new VTransferlist();
					BeanUtils.copyProperties(tl, vtl);

					if (tl.getUser() != null) {
						User user = tl.getUser();
						vtl.setUid(user.getId());
						vtl.setUname(user.getUsername());
					}
					if(tl.getItems()!=null){
						String gid = "";
						String itemsid = "";
						for(TransferlistItem it:tl.getItems()){
							gid += it.getGoods().getId()+",";		
							itemsid += it.getId()+",";
						}
						vtl.setIds(gid.substring(0,gid.length()-1));
						vtl.setItemsid(itemsid.substring(0,itemsid.length()-1));
					}
					if (tl.getInConfirmUser() != null) {
						User icu = tl.getInConfirmUser();
						vtl.setIcuid(icu.getId());
						vtl.setIcuname(icu.getUsername());
					}
					
					if (tl.getOutConfirmUser() != null) {
						User ocu = tl.getOutConfirmUser();
						vtl.setOcuid(ocu.getId());
						vtl.setOcuname(ocu.getUsername());
					}

					if (tl.getOutRepertory() != null) {
						Repertory or = tl.getOutRepertory();
						vtl.setOrid(or.getId());
						vtl.setOrname(or.getName());
					}

					if (tl.getInRepertory() != null) {
						Repertory ir = tl.getInRepertory();
						vtl.setIrid(ir.getId());
						vtl.setIrname(ir.getName());
					}


					vtls.add(vtl);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return vtls;
	}

	private List<Transferlist> find(VTransferlist vtl) {
		String hql = "select t from Transferlist t join t.items i where 1=1 ";

		List<Object> values = new ArrayList<Object>();
		hql = addWhere(vtl, hql, values);

		if (vtl.getSort() != null && vtl.getOrder() != null) {
			hql += " order by " + vtl.getSort() + " " + vtl.getOrder();
		}
		return transferlistDao.find(hql, values, vtl.getPage(), vtl.getRows());
	}

	private Long total(VTransferlist vtl) {
		try {
			String hql = " select count(*) from  (select count(*) from kcgl_transferlist t " +
					" , kcgl_transferlist_item i,rkgl_repertory ir ,rkgl_repertory ro ,qxgl_user u " +
					" where t.id=i.transfterlist_id and ir.id = t.in_repertory_id and " +
					" ro.id = t.out_repertory_id and t.user_id = u.id ";
			if (vtl.getId() != null) {
				hql += " and t.id = "+vtl.getId();
			}
			if (vtl.getSerial() != null) {
				hql += " and t.serial = "+vtl.getSerial();
			}

			if(vtl.getUpid()!=null){
				hql += " and u.user_id = "+vtl.getUpid();
			}else if (vtl.getUid() != null) {
				hql += " and (ir.user_id = "+vtl.getUid()+" or ro.user_id ="+vtl.getUid()+" )";
			}

			if (vtl.getOcuid() != null) {
				hql += " and t.out_confirm_user_id = "+vtl.getOcuid();
			}

			if (vtl.getIcuid() != null) {
				hql += " and t.in_confirm_user_id = "+vtl.getIcuid();
			}

			if (vtl.getBeginDate() != null) {
				hql += " and t.date >= "+vtl.getBeginDate();
			}

			if (vtl.getEndDate() != null) {
				hql += " and t.date <= "+vtl.getEndDate();
			}

			if (vtl.getIrid() != null) {
				hql += " and t.in_repertory_id = "+vtl.getIrid();
			}
			
			if(vtl.getRid()!=null){
				hql += " and t.in_repertory_id = "+vtl.getRid()+" or  t.out_repertory_id ="+vtl.getRid();
			}

			if (vtl.getOrid() != null) {
				hql += " and t.out_repertory_id = "+vtl.getOrid();
			}
			hql += " group by t.id order by date desc)aa";
			BigInteger a = transferlistDao.countSQL(hql);
			return a.longValue();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private String addWhere(VTransferlist vtl, String hql, List<Object> values) {
		if (vtl.getId() != null) {
			hql += " and t.id = ? ";
			values.add(vtl.getId());
		}

		if (vtl.getSerial() != null) {
			hql += " and t.serial = ? ";
			values.add(vtl.getSerial());
		}
		
		if (vtl.getUpid() != null) {
			hql += " and t.user.user.id = ? ";
			values.add(vtl.getUpid());
		}else if (vtl.getUid() != null) {
			hql += " and t.inRepertory.user.id = ? or t.outRepertory.user.id = ?";
			values.add(vtl.getUid());
			values.add(vtl.getUid());
		}

		if (vtl.getOcuid() != null) {
			hql += " and t.outConfirmUser.id = ? ";
			values.add(vtl.getOcuid());
		}

		if (vtl.getIcuid() != null) {
			hql += " and t.inConfirmUser.id = ? ";
			values.add(vtl.getIcuid());
		}

		if (vtl.getBeginDate() != null) {
			hql += " and t.date >= ? ";
			values.add(vtl.getBeginDate());
		}

		if (vtl.getEndDate() != null) {
			hql += " and t.date <= ? ";
			values.add(vtl.getEndDate());
		}

		if (vtl.getIrid() != null) {
			hql += " and t.inRepertory.id = ? ";
			values.add(vtl.getIrid());
		}
		
		if(vtl.getRid()!=null){
			hql += " and t.inRepertory.id = ? or  t.outRepertory.id = ?";
			values.add(vtl.getRid());
			values.add(vtl.getRid());
		}

		if (vtl.getOrid() != null) {
//			hql += " and ( t.outRepertory.id = ? or ( t.inRepertory.id = ? and t.isOutConfirm = ? ) ) ";
//			values.add(vtl.getOrid());
			hql += " and t.outRepertory.id = ?";
			values.add(vtl.getOrid());
			//values.add(true);
		}
		hql += " group by t.id";
		return hql;
	}

}
